import React, { useEffect, useState } from 'react';
import { DashboardMetricConfig, MetricData } from '@redfire/shared-types';

interface MetricCardProps {
  config: DashboardMetricConfig;
  onDataFetch?: (data: MetricData) => void;
}

const MetricCard: React.FC<MetricCardProps> = ({ config, onDataFetch }) => {
  const [data, setData] = useState<MetricData | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);

      // 构建API URL
      let url = `${config.apiEndpoint}`;
      if (config.indexCode) {
        url += `?code=${config.indexCode}`;
      }

      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      
      // 根据类型转换数据格式
      let metricData: MetricData;
      
      if (config.type === 'market_index' && result.success && result.data) {
        const indexData = result.data;
        metricData = {
          id: config.id,
          value: indexData.current?.toFixed(2) || '0.00',
          change: indexData.change?.toFixed(2) || '0.00',
          changePercent: indexData.change_percent || 0,
          trend: indexData.change_percent > 0 ? 'up' : indexData.change_percent < 0 ? 'down' : 'neutral',
          timestamp: indexData.timestamp || new Date().toISOString()
        };
      } else {
        // 默认格式
        metricData = {
          id: config.id,
          value: '暂无数据',
          trend: 'neutral'
        };
      }

      setData(metricData);
      onDataFetch?.(metricData);
    } catch (err) {
      console.error(`Failed to fetch data for ${config.displayName}:`, err);
      setError(err instanceof Error ? err.message : '数据加载失败');
      
      // 设置错误状态的数据
      setData({
        id: config.id,
        value: '--',
        trend: 'neutral'
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 初始加载
    fetchData();

    // 设置定时更新
    if (config.updateInterval && config.updateInterval > 0) {
      const intervalId = setInterval(fetchData, config.updateInterval);
      return () => clearInterval(intervalId);
    }
  }, [config]);

  const getTrendColor = (trend?: 'up' | 'down' | 'neutral'): string => {
    switch (trend) {
      case 'up':
        return '#52c41a';
      case 'down':
        return '#ff4d4f';
      default:
        return '#1890ff';
    }
  };

  const getTrendIcon = (trend?: 'up' | 'down' | 'neutral'): string => {
    switch (trend) {
      case 'up':
        return '↗';
      case 'down':
        return '↘';
      default:
        return '→';
    }
  };

  return (
    <div style={{
      backgroundColor: 'white',
      padding: '24px',
      borderRadius: '8px',
      boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
      borderLeft: `4px solid ${getTrendColor(data?.trend)}`,
      minHeight: '120px',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'space-between'
    }}>
      {/* 标题 */}
      <div style={{ 
        fontSize: '14px', 
        color: '#666', 
        marginBottom: '8px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <span>{config.displayName}</span>
        {loading && (
          <span style={{ fontSize: '12px', color: '#999' }}>更新中...</span>
        )}
      </div>

      {/* 主要数值 */}
      <div style={{ 
        fontSize: '28px', 
        fontWeight: 'bold', 
        color: '#333', 
        marginBottom: '4px',
        fontFamily: 'monospace'
      }}>
        {loading && !data ? (
          <span style={{ color: '#ccc' }}>--</span>
        ) : error ? (
          <span style={{ fontSize: '14px', color: '#ff4d4f' }}>加载失败</span>
        ) : (
          data?.value
        )}
      </div>

      {/* 涨跌信息 */}
      {config.showChange && data && !error && (
        <div style={{ 
          fontSize: '14px', 
          color: getTrendColor(data.trend),
          display: 'flex',
          alignItems: 'center',
          gap: '4px'
        }}>
          {config.showTrend && (
            <span style={{ fontSize: '16px' }}>{getTrendIcon(data.trend)}</span>
          )}
          <span>
            {data.change && `${parseFloat(data.change) >= 0 ? '+' : ''}${data.change}`}
            {data.changePercent !== undefined && ` (${data.changePercent >= 0 ? '+' : ''}${data.changePercent.toFixed(2)}%)`}
          </span>
        </div>
      )}

      {/* 错误提示 */}
      {error && (
        <div style={{ 
          fontSize: '12px', 
          color: '#ff4d4f',
          marginTop: '4px'
        }}>
          {error}
        </div>
      )}

      {/* 数据源标识 */}
      {config.dataSource && (
        <div style={{ 
          fontSize: '10px', 
          color: '#999',
          marginTop: '8px'
        }}>
          数据源: {config.dataSource}
        </div>
      )}
    </div>
  );
};

export default MetricCard;
